<template>
  <view class="container">
    <!-- 设备信息卡片 -->
    <view class="device-card">
      <view class="card-header">
        <image class="bluetooth-icon" src="../../static/image/lanya-icon.png"></image>
        <view class="battery-indicator">
          <text class="battery-value">{{ Math.round(vuex_bluetooth.voltage) }}%</text>
          <view class="battery-bar" :style="{ width: Math.round(vuex_bluetooth.voltage) + '%' }"></view>
        </view>
      </view>
      <view class="card-body">
        <view class="device-info">
          <text class="info-label">设备名称：</text>
          <text class="info-value">{{ vuex_bluetooth.deviceName }}</text>
        </view>
        <view class="device-info">
          <text class="info-label">设备MAC：</text>
          <text class="info-value">{{ vuex_bluetooth.deviceMac }}</text>
        </view>
        <view class="device-info">
          <text class="info-label">设备ID：</text>
          <text class="info-value">{{ vuex_bluetooth.deviceId }}</text>
        </view>
        <view class="device-info">
          <text class="info-label">设备厂商：</text>
          <text class="info-value">{{ vuex_bluetooth.deviceSupplier }}</text>
        </view>
        <view class="device-info">
          <text class="info-label">单/双环：</text>
          <text class="info-value">{{ vuex_bluetooth.deviceCategory }}</text>
        </view>
        <view class="device-info">
          <text class="info-label">蓝牙版本：</text>
          <text class="info-value">{{ vuex_bluetooth.deviceVersion }}</text>
        </view>
      </view>
    </view>

    <!-- 操作区域 -->
    <view class="action-section">
      <!-- 时间操作组 -->
      <view class="section-divider"></view>
      <view class="dual-buttons">
        <view class="btn btn-primary" @click="correctionTime">同步时间</view>
        <view class="btn btn-primary" @click="getTime">获取时间</view>
      </view>
      <view class="btn btn-secondary" @click="getBLEDevice">获取特征值</view>


      <!-- SN操作组 -->
      <view class="section-divider"></view>
      <view class="dual-buttons">
        <view class="btn btn-warning" @click="getSN">获取SN</view>
        <view class="btn btn-accent" @click="writeSN">写入SN</view>
      </view>
      <view class="input-group">
        <input class="sn-input" type="number" v-model="mySn" placeholder="请输入SN编码" placeholder-class="placeholder" />
      </view>

      <!-- 数据记录组 -->
      <view class="section-divider"></view>
      <view class="dual-buttons">
        <view class="btn btn-purple" @click="startRecord">开始记录</view>
        <view class="btn btn-purple" @click="stopRecord">暂停记录</view>
      </view>
      <view class="triple-buttons">
        <view class="btn btn-pink" @click="getDataCount">离线总数({{ numCount }})</view>
        <view class="btn btn-cyan" @click="getRealData">获取数据({{ percent }}%)</view>
        <view class="btn btn-danger" @click="stopRealData">终止获取</view>
      </view>


      <!-- 状态查询组 -->
      <view class="section-divider"></view>
      <view class="dual-buttons">
        <view class="btn btn-secondary" @click="isSynchronous">正在记录？</view>
        <view class="btn btn-secondary" @click="isRecord">正在同步？</view>
      </view>

      <!-- 设备管理组 -->
      <view class="section-divider"></view>
      <view class="dual-buttons">
        <view class="btn btn-danger" @click="shutdown">设备关机</view>
        <view class="btn btn-danger" @click="closeBlueAdapter">断开连接</view>
      </view>
      <view class="btn btn-warning" @click="clearData">清空数据</view>

      <!-- 设备管理组 -->
      <view class="section-divider"></view>
      <view class="dual-buttons">
        <view class="btn btn-danger" @click="openRed">开启红色</view>
        <view class="btn btn-danger" @click="closeRed">关闭红色</view>
      </view>
      <view class="btn btn-warning" @click="getBluetoothState">底座是否?</view>
      <view class="btn btn-purple" @click="onBLEChange">查看实时数据</view>

    </view>

    <!-- 设备管理组 -->
    <view class="section-divider"></view>


    <view class="charts-box">
      <view class="echarts-wrap">
        <!--				硬度百分比-->
        <qiun-data-charts type="line" :opts="stgOpts" :chartData="chartDataTop" :canvas2d="true" :ontouch="true"
          :onzoom="true" :animation="false" />
        <div class="echarts-wrap-text">
          <text>最大值：{{ currentTopMax }} 实时：{{ currentTop }} 最小值：{{ currentTopMin }}
            差(实时)：{{ (currentTop - currentTopMin) }} 差：{{ currentTopMax - currentTopMin }} 均：{{ currentTopAvg }}
          </text>
        </div>
      </view>
    </view>
  </view>
</template>

<script>

import { dateUtils, hexUtils } from '@/common/utils'
import { addReport } from "@/common/commitReport";

export default {
  computed: {
    vuex_bluetooth() {
      return getApp().globalData.bluetooth
    }
  },
  data() {
    return {
      historyData: [],
      mySn: "0120250131010000",
      percent: 0,
      numCount: 0,

      stgOpts: {
        update: true,
        color: ['#008004'],
        padding: [15, 35, 0, 5],
        touchMoveLimit: 24,
        enableScroll: true,
        dataLabel: false,
        xAxis: {
          itemCount: 600,
          scrollAlign: 'right',
          lableCount: 9, //单屏幕限制显示的数量
          disableGrid: true, //不绘制纵向网格
          scrollShow: false, //是否显示滚动条
          scrollColor: '#fecb10', //滚动条颜色
          // itemCount: 59,//单屏数据密度
          // itemCount: 1000,
          rotateLabel: true, //【旋转】数据点（刻度点）
          // rotateAngle: 90,//【旋转】数据点（刻度点）角度
          // scrollAlign: 'right',//滚动条初始位置
          fontSize: 10 //数据点（刻度点）字体大小
        },

        yAxis: {
          // splitNumber: 5,
          // data: [{
          // 	min: 0,
          // 	max: 100,
          // 	unit: '%'
          // }]
        },
        extra: {
          line: {
            type: "straight",
            width: 0
          }
        }
      },
      chartDataTop: {
        categories: [],
        series: [{
          name: 'Top电压',
          data: []
        }]
      },
      openId: undefined,
      currentTop: 0,
      currentTopMax: 0,
      currentTopMin: 0,
      currentTopAvg: 0,


      currentRoot: 0,
      currentRootMax: 0,
      currentRootMin: 0,
      isTwo: false,


      topArr: [],
      rootArr: [],
      currentDate: undefined,
      hexs: [],
    };
  },
  onReady() {
    console.log('ready....', this.vuex_bluetooth);
  },
  onShow() {
    console.log('show....');
    this.mySn = hexUtils.generateDateString()
    console.log('show....', this.vuex_bluetooth);

    // 检查蓝牙连接状态后再执行操作
    if (this.vuex_bluetooth && this.vuex_bluetooth.isLink && this.vuex_bluetooth.deviceId) {
      console.log("同步时间...");
      this.correctionTime();
    } else {
      console.log("蓝牙未连接，跳过自动同步时间");
    }
  },
  onUnload() {
    clearInterval(this.timer);
  },
  methods: {

    getSN() {
      console.log('获取当前SN');
      this.$BluetoothUtils.getSN(this.vuex_bluetooth);
    },

    writeSN() {
      console.log('写入指定SN', this.mySn);
      this.$BluetoothUtils.writeSN(this.vuex_bluetooth, this.mySn);
    },

    // 同步当前时间
    correctionTime() {
      this.$BluetoothUtils.correctionTime(this.vuex_bluetooth);
    },
    getTime() {
      console.log('获取当前蓝牙模块时间....')
      this.$BluetoothUtils.getTime(this.vuex_bluetooth);
    },
    getBLEDevice() {
      this.$BluetoothUtils.getBLEDevice(this.vuex_bluetooth);
    },
    // 监听监听Notification变化
    onBLEChange() {
      this.$BluetoothUtils.onBLEChange(this.vuex_bluetooth);
      this.getBluetoothData();
    },
    // 开始记录数据
    startRecord() {
      this.$BluetoothUtils.startRecord(this.vuex_bluetooth);
    },
    // 停止记录数据
    stopRecord() {
      this.$BluetoothUtils.stopRecord(this.vuex_bluetooth);
    },
    // 获取离线总数
    getDataCount() {
      this.$BluetoothUtils.getDataCount(this.vuex_bluetooth).then(numCount => {
        console.log("条数：", numCount)
        this.numCount = numCount
      }).catch(res => {
        console.log(res);
      });
    },
    // 开始同步蓝牙数据
    getRealData() {
      let that = this;
      that.$BluetoothUtils.getRealData(that.vuex_bluetooth, {
        syncPercent: (p) => {
          that.percent = p;
        }
      }).then(res => {
        console.log('获取蓝牙离线数据 结束....', res);
        let hexArr = res

        // 构建提交数据 - 根据数据库表结构优化
        let data = {
          openId: uni.getStorageSync('openId') || null,
          deviceMac: this.vuex_bluetooth.deviceMac,
          deviceId: this.vuex_bluetooth.deviceId,
          reportNum: this.vuex_bluetooth.deviceName || 'YG-01',
          hexs: JSON.stringify(hexArr),
          arrData: null,  // 原始数据，暂时为空
          arrTemp: null,  // 备用字段，暂时为空
          arrTimestamp: new Date().getTime().toString(), // 时间戳
          remark: '蓝牙设备数据同步'
        };

        // 输出设备信息到控制台，格式与图片一致
        console.log("设备信息:", {
          deviceMac: this.vuex_bluetooth.deviceMac,
          deviceId: this.vuex_bluetooth.deviceId,
          reportNum: this.vuex_bluetooth.deviceName || 'YG-01',
          hexs: hexArr
        });

        // 发送数据到后台
        console.log("发送请求数据:", JSON.stringify(data, null, 2));

        addReport(data).then(response => {
          console.log("数据保存成功:", response);
          uni.showToast({
            title: '数据保存成功',
            icon: 'success',
            duration: 2000
          });

          // 重置进度
          that.percent = 0;
        }).catch(error => {
          console.error("数据保存失败，详细错误信息:", error);
          console.error("错误类型:", typeof error);
          console.error("错误内容:", JSON.stringify(error, null, 2));

          let errorMessage = '数据保存失败';
          if (error && error.msg) {
            errorMessage = error.msg;
          } else if (error && error.message) {
            errorMessage = error.message;
          } else if (typeof error === 'string') {
            errorMessage = error;
          }

          uni.showToast({
            title: errorMessage,
            icon: 'error',
            duration: 3000
          });
        });
      }).catch(reason => {
        console.error('获取蓝牙数据失败:', reason);
        uni.showToast({
          title: '获取数据失败',
          icon: 'error',
          duration: 2000
        });
      });
    },
    // 终止同步蓝牙数据
    stopRealData() {
      this.$BluetoothUtils.stopRealData(this.vuex_bluetooth);
    },
    // 是否同步
    isSynchronous() {
      this.$BluetoothUtils.isSynchronous(this.vuex_bluetooth);
    },
    // 是否记录
    isRecord() {
      this.$BluetoothUtils.isRecord(this.vuex_bluetooth);
    },
    // 清空数据
    clearData() {
      this.$BluetoothUtils.clearData(this.vuex_bluetooth);
    },
    // 关机
    shutdown() {
      this.$BluetoothUtils.shutdown(this.vuex_bluetooth);
    },
    // 断开蓝牙链接
    closeBlueAdapter() {
      this.$BluetoothUtils.closeBlueAdapter(this.vuex_bluetooth);
    },
    // 蓝牙是否连接底座
    getBluetoothState() {
      this.$BluetoothUtils.getBluetoothState(this.vuex_bluetooth);
    },
    // 开启红色
    openRed() {
      this.$BluetoothUtils.openRed(this.vuex_bluetooth);
    },
    // 关闭红色
    closeRed() {
      this.$BluetoothUtils.closeRed(this.vuex_bluetooth);
    },


    // 获取蓝牙数据
    initBluetoothData(dataMap) {
      console.log("执行初始化...");
      let that = this
      uni.onBLECharacteristicValueChange(function (characteristic) { //时间大概是 2.5 - 3.5
        // that.deviceId = characteristic.deviceId;
        let timer = setInterval(() => {
          let hex = Array.prototype.map.call(new Uint8Array(characteristic.value), x => (
            '00' + x.toString(16)).slice(-2)).join('');

          let version = hex.length
          if (version === 8) {
            let hexDate = dateUtils.getTimestamp().toString(16);
            that.vuex_bluetooth.deviceCategory = 'one';
            // 蓝牙1.0电压
            let hexData = hex.substring(0, 4);

            let khwHex = hex.substring(4, 8);
            let voltage = hexUtils.convertHexTo10(khwHex);

            console.log("电压：", voltage)


            dataMap.set(dateUtils.getDateTime(), '0000' + hexDate + '0000' + hexData);

          }
        }, 200);
        let _setTimeout = setTimeout(function () {
          clearInterval(timer);
          clearInterval(_setTimeout);
        }, 3000);
      });
    },

    /**
     * 获取蓝牙数据
     */
    getBluetoothData() {
      let that = this;
      console.log("获取蓝牙数据...");
      let dataMap = new Map()
      this.initBluetoothData(dataMap);


      that.currentDate = dateUtils.getTimestamp();
      // 更新秩序时间
      setInterval(() => {
        that.durationTime = dateUtils.getTimestamp() - that.currentDate;
        that.durationTimeStr = dateUtils.convertTime(that.durationTime);
      }, 1000);

      that.timer = setInterval(() => {

        let hex = dataMap.get(dateUtils.getDateTimeMinus1Second());

        if (hex) {
          that.hexs.push(hex)
          console.log("hex:", hex);
        }

        if (that.vuex_bluetooth.deviceCategory == 'two') {
          that.isTwo = true;
          if ((hex) && hex != '01') {

            let hexData1 = hex.substring(12, 16);
            let hexData2 = hex.substring(16, 20);
            // let kwhTemp = hex.substring(8, 12);


            let data1 = hexUtils.convertHexTo10(hexData1);
            let data2 = hexUtils.convertHexTo10(hexData2);
            // let kwh = hexUtils.convertHexTo10(kwhTemp); // 电压


            that.topArr.push(data1);
            that.rootArr.push(data2);


            console.log("实时数据 data1:", data1, "实时数据 data2:", data2);


            that.currentTop = data1;
            that.currentTopMax = Math.max(...that.topArr);
            that.currentTopMin = Math.min(...that.topArr);

            const sum = that.topArr.reduce((acc, val) => acc + val, 0);
            that.currentTopAvg = (sum / that.topArr.length).toFixed(0);

            that.currentRoot = data2;
            that.currentRootMax = Math.max(...that.rootArr);
            that.currentRootMin = Math.min(...that.rootArr);

            that.chartDataTop.series[0].data.unshift(data1);
            that.chartDataRoot.series[0].data.unshift(data2);

            // 处理下标 删除超过600的数据
            that.verifyChats(that.durationTime);
          }
        } else {
          that.isTwo = false
          if ((hex) && hex != '01') {

            // let dataTemp = hex.substring(0, 4);

            let dataTemp = hex.substring(16, 20);

            let data = hexUtils.convertHexTo10(dataTemp); // 电压值
            // let kwh = hexUtils.convertHexTo10(kwhTemp); // 电压

            console.log("实时数据", data);

            // 获取当前时间戳
            let currentTime = Math.floor(Date.now() / 1000);

            that.topArr.push(data);

            // console.log("实时数据 data1:", data);

            that.currentTop = data;
            that.currentTopMax = Math.max(...that.topArr);
            that.currentTopMin = Math.min(...that.topArr);

            const sum = that.topArr.reduce((acc, val) => acc + val, 0);
            that.currentTopAvg = (sum / that.topArr.length).toFixed(0);


            that.chartDataTop.series[0].data.unshift(data);
            // 处理下标 删除超过600的数据
            that.verifyChats(that.durationTime);

          }
        }
        // 	}
      }, 100);
    },

    /**
     * 更新时间
     * 删除超过600个数据点
     * @param currentTime
     */
    verifyChats(currentTime) {
      let that = this;
      let timeStr = '';
      let historyLength = that.topArr.length

      // 1.如何数据 小于600条 则每50条展示时间
      if (historyLength < 600 && historyLength % 50 === 0) {
        timeStr = dateUtils.convertTime(currentTime);
      }
      // 2.如果数据 大于600条 则每100条展示时间
      if (historyLength >= 600 && historyLength % 100 === 0) {
        timeStr = dateUtils.convertTime(currentTime);
      }

      // 处理下标是一致的
      that.chartDataRoot.categories.unshift(timeStr);
      that.chartDataTop.categories.unshift(timeStr);
      // 插入对应数组

      let arrLength = that.chartDataRoot.series[0].data.length;
      // 处理数据大于600条删除
      if (arrLength > 600) {
        // 实时数据
        that.chartDataRoot.categories.splice(-1, 1);
        that.chartDataRoot.series[0].data.splice(-1, 1);
        // 硬度数据
        that.chartDataTop.categories.splice(-1, 1);
        that.chartDataTop.series[0].data.splice(-1, 1);
        // 胀大数据
        // that.chartDataTop.categories.splice(-1, 1);
        // that.chartDataTop.series[0].data.splice(-1, 1);
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.container {
  background: #f8f9fa;
  padding: 24rpx;
  min-height: 100vh;
}

/* 设备卡片样式 */
.device-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  margin-bottom: 32rpx;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;

    .bluetooth-icon {
      width: 96rpx;
      height: 96rpx;
      filter: drop-shadow(0 2rpx 4rpx rgba(0, 0, 0, 0.1));
    }

    .battery-indicator {
      position: relative;
      width: 120rpx;
      height: 40rpx;
      background: #e9ecef;
      border-radius: 8rpx;
      overflow: hidden;

      .battery-value {
        position: absolute;
        z-index: 2;
        font-size: 24rpx;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        color: #495057;
        font-weight: 500;
      }

      .battery-bar {
        position: absolute;
        height: 100%;
        background: linear-gradient(90deg, #4cd964, #34c759);
        transition: width 0.3s ease;
      }
    }
  }

  .card-body {
    .device-info {
      margin-bottom: 16rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;

      .info-label {
        color: #6c757d;
        min-width: 160rpx;
      }

      .info-value {
        color: #212529;
        font-weight: 500;
        word-break: break-all;
      }
    }
  }
}

/* 操作区域样式 */
.action-section {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

  .section-divider {
    height: 2rpx;
    background: linear-gradient(90deg, transparent, #dee2e6 50%, transparent);
    margin: 40rpx 0;
  }

  /* 按钮基础样式 */
  .btn {
    height: 88rpx;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    font-weight: 500;
    transition: all 0.2s ease;
    margin: 12rpx 0;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    padding: 0 20rpx;

    /* 按钮颜色变体 */
    &-primary {
      background: #3b71fe;
      color: white;

      &:active {
        background: #2954c7;
      }
    }

    &-secondary {
      background: #6c757d;
      color: white;
    }

    &-info {
      background: #17a2b8;
      color: white;
    }

    &-warning {
      background: #ffc107;
      color: #212529;
    }

    &-danger {
      background: #dc3545;
      color: white;
    }

    &-purple {
      background: #6f42c1;
      color: white;
    }

    &-pink {
      background: #e83e8c;
      color: white;
    }

    &-cyan {
      background: #0dcaf0;
      color: #212529;
    }

    &-accent {
      background: #fd7e14;
      color: white;
    }
  }

  /* 并排按钮布局 */
  .dual-buttons {
    display: flex;
    gap: 24rpx;
    margin: 12rpx 0;

    .btn {
      flex: 1 1 0;
      margin: 0;
      min-width: 0;
    }
  }

  .triple-buttons {
    display: flex;
    gap: 18rpx;
    margin: 12rpx 0;

    .btn {
      flex: 1 1 0;
      margin: 0;
      min-width: 0;
      font-size: 26rpx;
    }
  }

  /* 输入框样式 */
  .input-group {
    margin: 24rpx 0;

    .sn-input {
      width: 100%;
      height: 88rpx;
      padding: 0 24rpx;
      border: 2rpx solid #dee2e6;
      border-radius: 12rpx;
      font-size: 28rpx;
      background: #ffffff;
      margin-bottom: 16rpx;

      &:focus {
        border-color: #3b71fe;
        box-shadow: 0 0 8rpx rgba(59, 113, 254, 0.25);
      }
    }
  }
}

/* 占位符样式 */
.placeholder {
  color: #adb5bd;
  font-size: 28rpx;
}

/* 安全区域 */
.safe-area {
  height: env(safe-area-inset-bottom);
  padding-bottom: constant(safe-area-inset-bottom);
}

.charts-box {
  .echarts-wrap {
    width: 100%;
    height: 600rpx;
    margin-top: 40rpx;

    .echarts-wrap-text {
      display: flex;
      justify-content: center;
      font-weight: 600;
      font-size: 24rpx;
      min-width: auto;
    }
  }
}
</style>
